<template>
    <div>
      <div class="shopcart">
       <!--触发购物车列表的展示与隐藏 -->
       <div class="content" @click="togglelist">
           <div class="content-left">
               <div class="logo-wrapper">
                   <!--高亮颜色设置 -->
                   <div class="logo" :class="{'highLight' : totalCount > 0}">
                       <!--固定标签i的使用 -->
                      <i class="icon-shopping_cart" :class="{'highLight' : totalCount > 0}"></i>
                   </div>
                   <!--computed属性的价格值 -->
                   <div class="num" v-show="totalCount > 0">{{totalCount}}</div>
               </div>
               <!--computed属性的价格值 -->
               <div class="price" :class="{'highLight' : totalCount > 0}">￥{{totalPrice}}</div>
               <div class="desc">另需配送费￥{{deliveryPrice}}元</div>
           </div>
           <div class="content-right">
                <!--computed属性的样式payClass与字符串payDesc 阻止pay事件出现冒泡-->
               <div class="pay" :class="payClass" @click.stop.prevent="pay">{{payDesc}}</div>
           </div>
       </div>
       <!--抛物小球 -->
       <div class="balls-wrapper">
         <!-- <transition class="drop">
           外层 循环小球的展示ball.show 
           <div v-for="(ball,index) in balls"  v-show="ball.show" class="ball"></div>
           内层 
           <div class="inner"></div>
         </transition> -->
          <div v-for="(ball,index) in balls" :key="index">
          <!--调用transition钩子函数 -->
          <transition name="drop" @before-enter="beforeDrop" @enter="dropping" @after-enter="afterDrop">
            <!--外层 循环小球的展示ball.show -->
            <div class="ball" v-show="ball.show">
              <!--内层 -->
              <div class="inner inner-hook"></div>
            </div>
          </transition>
        </div>
       </div>
       <!--购物车列表弹出层 computed属性listShow进行关联初始化-->
       <transition name="fade">
       <div class="shopcart-list" v-show="listShow">
         <div class="list-header">
            <div class="title"><span>购物车</span></div>
            <div class="empty" @click="empty">清空</div>
         </div>
         <!--绑定better-scoll滚动 -->
         <div class="list-content" ref="listContent">
          <ul>
            <!--被选择的商品集合selectFoods -->
            <li v-for="(food,index) in selectFoods" :key="index" class="food">
             <span class="name">{{food.name}}</span>  
             <!-- <div class="price">￥{{food.price * food.count}}</div> -->
             <div class="price">
              <span class="totalPrice"><span class="sign">￥</span>{{food.price * food.count}}</span>
              </div>
             <div class="cartcontrol-wrapper">
                <!-- 必须传:food="food"，cartcontrol组件才生效 -->
                <cartcontrol :food="food"  @addCart="addFoodShop"></cartcontrol>
             </div>                        
            </li>
          </ul>
         </div>
       </div>
       </transition>
    </div>
      <!--购物车背景色 -->
      <transition name="mask">
        <div class="list-mask" v-show="listShow" @click="hideList"></div>
      </transition>
    </div>
</template>

<script>
import BScroll from 'better-scroll';
import cartcontrol from '../base/cartcontrol/cartcontrol.vue';

export default {
    props: {
        /**
         * 选择的商品存放到selectFodds数组,统计数组中的数量与总价
         */
      selectFoods:{
          type: Array,
          default() {
            return [];  
          }
      },  
      deliveryPrice : {
          type: Number,
          default: 0
      },
      minPrice : {
          type: Number,
          default: 0
      }
    },
    components: {
      cartcontrol
    },
    data() {
        return {
          balls:[{
            show: false  
          },{
            show: false  
          },{
            show: false  
          },{
            show: false  
          },{
            show: false  
          }],//抛物5个小球 解决在前一个小球没有下落后又点击的问题
          dropBalls:[], //下落的小球
          fold:true//购物车列表展示 默认折叠
        };
    },
    computed: {
      // 初始默认值
      totalPrice() {
        let price = 0;
        this.selectFoods.forEach((food) => {
          price += food.price * food.count;
        });
        return price;
      },
      totalCount() {
        let count = 0;
        this.selectFoods.forEach((food) => {
          count += food.count;
        });
        return count;
      },
      //三种状态 1.起送 2.还差￥10元起送 3.去结算
      payDesc() {
        // 读取computed中的tatalPrice属性
        if (this.totalPrice === 0) {
            return `￥${this.minPrice}元起送` //es6模板
        }else if (this.totalPrice < this.minPrice) {
            let diff = this.minPrice - this.totalPrice ;
            return `还差￥${diff}元起送`
        }else {
            return '去结算';
        }
      },
      payClass() {
        if (this.totalPrice < this.minPrice) {
            return 'no-enough';
        }else {
            return 'enough';
        }
      },
      //购物车列表展示
      listShow() {
          console.log('listshow的触发方法this.totalCount ' + this.totalCount);
        if(!this.totalCount){
          this.fold = true;
          return false;
        }
          let show = !this.fold;
          //如果展示,初始化滚动条
          if(show){
            //渲染dom的变化,使用this.$nextick()
            this.$nextTick(() => {
             if(!this.shopcartListScroll){
                console.log('第一次初始化购物车滚动条');
                // let shopcartListScroll =  new BScroll(this.$refs.listContent,{//获取当前的dom对象
                //     click:true //启动click事件
                // });
                //定义成this否则触发cartcontrol子组件数量递增
                this.shopcartListScroll =  new BScroll(this.$refs.listContent,{//获取当前的dom对象
                  click:true //启动click事件
                });
             }else{
                console.log('根据每次toggle计算高度来决定能否滚动');
                this.shopcartListScroll.refresh();
             }
            });
          }
          return show;
      }
    },
    methods: {
      //父组件goods传递到shopcart组件的drop()方法
      drop(target) { // 拿到cartcontrol点击的元素
        console.log('再将goods父组件中的dom传递到shopcart子组件里');
        console.log(target);
        for(let i=0;i<this.balls.length;i++) {
            let ball = this.balls[i];
           if(!ball.show){
             ball.show = true;// 循环所有ball，找出未show
             ball.target = target;//这个为了计算小球的高度
             this.dropBalls.push(ball);
             return;
           } 
        }
      },
      // 小球执行步骤:
      // 1. 点击cartcontrol组件中的”加号按钮“，$emit添加触发事件，将event.target作为参数，由goods父组件监听
      // 2. goods组件接收事件和target，执行_drop(target)，调用shopcart子组件的drop(el)方法，传入了target
      // 3. shopcart 组件执行 drop(el) 方法时，获取el在视口中的位置，编程式调用ball元素的过渡hook接口，执行css过渡
      // 动画的原理是先把它偏移到一个位置，然后按照一定的轨迹和时间完成动画，动画完成后要把位置重置
      beforeDrop(target) { 
        // target是Vue 钩子选择作用动画的 DOM 对象
        console.log('transition钩子函数选择动画的dom对象');
        console.log(target);
        let count = this.balls.length;
        for(let i=0;i<count;i++){
          let ball = this.balls[i]; //初始下落的小球位置
          if(ball.show){
            let rect = ball.target.getBoundingClientRect(); // 得到元素距视口各边的偏移量
            // 是相对于小球初始位置的，所以 x 是正的，y 是负的
            let x = rect.left - 32;
            let y = -(window.innerHeight - rect.top - 36);
            //target是dom元素
            target.style.display = '';// 手动设置为空，小球会显示出来
            target.style.webkitTransformOriginY = `translate3d(0,${y}px,0)`;
            target.style.transform = `translate3d(0,${y}px,0)`;
            let inner = target.getElementsByClassName('inner-hook')[0];//而不是target.getElementsByClassName('inner-hook')
            console.log('beforeDrop获取target中的内层元素inner');
            console.log(inner);
            inner.style.webkitTransformOriginX = `translate3d(${x}px,0,0)`;
            inner.style.transform = `translate3d(${x}px,0,0)`;
          }
        }
      },
      dropping(target,done) {// Vue enter 的第二个参数必须给，否则会设置成同步
        let rf = target.offsetHeight;
        // 触发浏览器重绘，使用回调函数可以保证 dom 位置渲染正确后再执行之后的动画
        this.$nextTick(() => {
          target.style.webkitTransformOriginY = 'translate3d(0,-10px,0)'; //字符串中没有变量传递的话使用''，若存在变量则使用模板``
          target.style.transform = 'translate3d(0,-10px,0)';
          let inner = target.getElementsByClassName('inner-hook')[0];
          console.log('dropping获取target中的内层元素inner');
          console.log(inner);
          inner.style.webkitTransformOriginX = 'translate3d(0,0,0)';
          inner.style.transform = 'translate3d(0,0,0)';
           // 告知Vue，一个小球动画完成
          target.addEventListener('transitionend', done);   // 当动画结束，会有  CSS3 transitionend 事件派发
        });
      },
      afterDrop(target) {
        // 首先触发afterDrop是最先落的小球，所以把第一项也就是先落的小球重置
        let ball = this.dropBalls.shift();//删除dropBalls第一项，并返回此项
        if(ball.show){
          ball.show = false;
          target.style.display = 'none';
        }
      },
      //购物车弹出层调用小球抛物效果
      addFoodShop(target) {
        console.log('触发addFoodShop()方法添加抛物小球效果');
        console.log(target);
        this.$emit('addCart', target);
      },
      //购物车列表展示
      togglelist() {
          console.log('触发togglelist事件   ' + this.totalCount);
        if(this.totalCount){
          console.log('点击是否执行togglelist   ' + this.totalCount);
          this.fold = !this.fold;
        }
      },
      empty() {
        this.selectFoods.forEach((food) =>{
          food.count = 0;
        });
      },
      hideList() {
        this.fold = true;//隐藏背景
      },
      //去支付
      pay() {
        if(this.totalPrice < this.minPrice){
            return;
        } 
       window.alert(`请支付${this.totalPrice + this.deliveryPrice}元`);
      }
    }
}
</script>

<style lang="scss" rel="stylesheet/scss">
@import "../../assets/style/mixin.scss";

.shopcart {
    position: fixed;//底部固定,而不是display:flex;
    bottom: 0;
    left: 0;
    // background:#141d27;//若背景色控制在这里,则弹出购物车列表的时候，去结算位置会有一个灰色效果先展示出来
    width: 100%;
    height: 48px;
    z-index: 10;
    .content {
      display: flex; 
      background:#141d27;
      color: rgba(255, 255, 255, 0.4);
      .content-left {
        flex: 1;
        .logo-wrapper {
          display: inline-block;
          position: relative;//相对位置
          vertical-align: top;
          margin: 0 12px; // (36-12)/2
          padding: 6px;
          top:-10px;//突出部分
          width: 56px;// (88 + 12 + 12 )/2
          height: 56px;
          box-sizing: border-box;//不设置显示不了圆形
          border-radius: 50%;//设置圆形
          background: #141d27;//没有设置背景色显示不了效果
          //设置屏幕的兼容性,内容多大显示不了
          @media only screen and (max-width: 320px) {
            margin-left: 6px;
            margin-right: 0px;
          }
          .logo {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: #2b343c;
            text-align: center;//居中
            &.highLight {
              //高亮设置
              background-color: rgb(0,160,220);
            }
            .icon-shopping_cart {
              font-size: 24px;
              line-height: 44px;//why?
              color: #80858a;
              &.highLight {
              //高亮设置
                color: #fff;
              }
            }
          }
          .num {
            position: absolute;//绝对定位,设置top,right,同时设置width,height
            top: 0;
            right: 0;
            width: 24px;
            height: 16px;
            line-height: 16px;
            text-align: center;
            border-radius: 12px;
            font-size: 9px;
            font-weight: 700;
            background-color: rgb(240,20,20);
            box-shadow: 0 1px 0 2px rgba(0,0,0,0.2); //设置阴影
            color: rgb(255,255,255);
          }
        }
        .price {
          display: inline-block;
          vertical-align: top;
          margin-top: 12px;
          padding-right: 12px;
          line-height: 24px;
          font-size: 16px;
          font-weight: 700;
          box-sizing: border-box;
          color: rgba(255, 255, 255,0.4);
          border-right: 1px solid rgba(255, 255, 255, 0.1);
          @media only screen and (max-width: 320px) {
            padding-right: 6px;
          }
          &.highLight {
            //高亮设置
            color: #fff;
          }
        }
        .desc {
          display: inline-block;
          vertical-align: top;
          margin: 12px 0 0 12px;
          line-height: 24px;
          font-size: 12px;
          box-sizing: border-box;
          color: rgba(255, 255, 255,0.4);
          //设置屏幕的兼容性,内容多大显示不了
          @media only screen and (max-width: 320px) {
            margin: 12px 0 0 6px;
            font-size: 10px;
          }
        }
      }
      .content-right {
        flex: 0 0 105px;
        width: 105px;
        background: rgba(0, 0, 0,0.2);
        //设置屏幕的兼容性,内容多大显示不了
        @media only screen and (max-width: 320px) {
          flex: 0 0 95px;
          width: 95px;
        }
        .pay {
          display: inline-block;
          text-align: center;
          margin-left: 8px;
          width: 100%;
          height: 50px;
          line-height: 50px;
          font-size: 12px;
          font-weight: 700;
          // 没有达到起步价
          &.no-enough {
            color: rgba(255, 255, 255,0.4);
          }
          // 达到结算
          &.enough {
            background: #00b43c;
            color: #fff;
          }
        }
      }
    }
    .balls-wrapper {
      .ball {
        position: fixed;//固定
        left:32px;
        bottom: 22px;
        z-index: 200;//购物车上层
        &.drop-enter-active{ // ball与drop是同级别
          transition: all 0.5s cubic-bezier(.49, -0.29, .75, .41);//曲线环动
          .inner {
            transition: all 0.5s linear;//线性环动 
          } 
        }
        .inner {
          width: 16px;
          height: 16px;
          border-radius: 50%;
          background-color: rgb(0,160,220);
        }
      }
    }
    .shopcart-list {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 100%;
      transform: translate3d(0,-100%,0);//自适应高度 --- 如果放到fade-enter中则显示一下就消失
      &.fade-enter-active,&.fade-leave-active {
        transition: all 0.5s;
      }
      &.fade-enter,&.fade-leave-to {
        transform: translate3d(0,0,0);
      }
      .list-header {
        height: 40px;
        line-height: 40px;
        padding: 0 18px;
        background: #f3f5f7;
        border: 1px solid rgba(7, 17, 27,0.2);
        .title {
          float: left;
          font-size: 14px;
          font-weight: 700;
          color: rgb(7,17,27);
          span {
            border-left: 3px solid #2d97fc;
            padding-left: 5px;
          }
        }
        .empty {
          float: right;
          font-size: 12px;
          color: rgb(0,160,220);
        }
      }
      .list-content {
        height: 217px;
        padding: 0 18px;
        overflow: hidden;//overflow:auto，超出部分出现滚动条
        background: #fff;
        .food {
          position: relative;
          box-sizing: border-box;
        //   height: 48px;
        //   line-height: 48px; //写高度容易变形
          padding: 12px 0;
          @include border-1px(rgba(7, 17, 27, 0.1)); //设置1像素
          .name {
            font-size: 14px;
            line-height: 24px;
            color: rgb(7,17,27);
          }
          .price {
            position: absolute;//固定 
            right: 90px;
            bottom: 12px;
            line-height: 24px;
            color: rgb(240,20,20);
            .totalPrice {
              font-size: 16px;
              font-weight: 900;
              .sign {
                font-size: 11px;
                font-weight: 900;
              }
            }
          }
          .cartcontrol {
            position: absolute;
            right: 0;
            bottom: 2px;
          }
        }
      }
    }
}
.list-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 4;//
  -webkit-backdrop-filter: blur(10px);//针对ios浏览器
  background: rgba(0, 0, 0, 0.5);
  &.mask-enter-active,&.mask-leave-active {
    opacity: 1;
    transition: all 0.5s; //浮动效果
  }
  &.mask-enter,&.mask-leave-to {
    opacity: 0; //透明度消失
    background: rgba(0, 0, 0, 0);
  }
}

</style>
